#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1e3 + 10;
int n, m;
int g[N][N];
int dis[N][N];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
int main()
{
	cin >> n >> m;
	queue<PII>q;
	int good = 0;
	memset(dis, -1, sizeof(dis));
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> g[i][j];
			if (g[i][j] == 1)good++;
			else if (g[i][j] == 2) {
				q.push({ i,j });
				dis[i][j] = 0;
			}
		}
	}
	while (q.size()) {
		PII t = q.front();
		q.pop();
		/*cout << "a===" << t.x << endl;
		cout << "b===" << t.y << endl;*/
		for (int i = 0; i < 4; i++) {
			int a = dx[i] + t.x;
			int b = dy[i] + t.y;
			if (a <= 0 || a > n || b <= 0 || b > m)continue;
			if (!g[a][b])continue;
			if (dis[a][b] != -1)continue;
			dis[a][b] = dis[t.x][t.y] + 1;
			q.push({ a,b });
			g[a][b] = 2;
		}
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			if (dis[i][j] != -1 && dis[i][j] != 0) {
				//cout << dis[i][j] << endl;
				ans = max(ans, dis[i][j]);
			}
			if (g[i][j] == 1) {
				cout << -1 << endl;
				return 0;
			}
		}
	}
	cout << ans << endl;
	return 0;
}